package com.henry.imkit.models

import com.henry.imkit.*
import com.henry.imkit.utils.IMLog
import com.henry.imkit.utils.IMLogErr
import com.henry.imkit.utils.MD5Utils
import io.realm.Realm
import io.realm.RealmConfiguration
import io.realm.kotlin.where

object RealmHelper {

    private var mRealm: Realm? = null

    private fun getRealm(): Realm {
        if (mRealm == null) {
            val realmName = MD5Utils.getMD5(IMKit.instance.domain + IMManager.userId)
            IMLog("realm name: $realmName")
            val config = RealmConfiguration.Builder()
                    .name(realmName)
                    .schemaVersion(0)
                    .build()
            mRealm = Realm.getInstance(config)

        }
        return mRealm!!
    }

    fun onDestroy() {
        mRealm?.close()
        mRealm = null
    }

    fun save(list: List<Conversation>) {
        getRealm().executeTransactionAsync {
            it.copyToRealmOrUpdate(list)
        }
    }

    fun save(conv: Conversation) {
        getRealm().executeTransactionAsync {
            it.copyToRealmOrUpdate(conv)
        }
    }

    fun update(id: String, lastDisplay: String, lastTime: Long, unRead: Int, success: OnSuccessCallback? = null) {
        getRealm().executeTransactionAsync({
            val inner: Conversation = it.where<Conversation>().equalTo("id", id).findFirst()!!
            inner.lastMessageDisplay = lastDisplay
            inner.lastMessageTime = lastTime
            inner.unRead = unRead
            it.copyToRealmOrUpdate(inner)
        }, {
            success?.invoke()
        }, {
            IMLogErr(it.toString())
        })
    }

    fun find(id: String) {
        getRealm().executeTransactionAsync {
            val inner: Conversation = it.where<Conversation>().equalTo("id", id).findFirst()!!
        }
    }

    fun findAll(): List<Conversation> {
        return getRealm().where<Conversation>().findAll()
    }

    fun delete(id: String, success: OnSuccessCallback? = null) {
        getRealm().executeTransactionAsync({
            val inner: Conversation = it.where<Conversation>().equalTo("id", id).findFirst()!!
            inner.deleteFromRealm()
        }, {
            success?.invoke()
        }, {
            IMLogErr(it.toString())
        })
    }

    fun delete(conv: Conversation, success: OnSuccessCallback? = null) {
        getRealm().executeTransactionAsync({
            val inner: Conversation = it.where<Conversation>().equalTo("id", conv.id).findFirst()!!
            inner.deleteFromRealm()
        }, {
            success?.invoke()
        }, {
            IMLogErr(it.toString())
        })
    }

    fun handleEvent(event: IMEvent?, success: OnSuccessCallback? = null) {
        if (event == null) {
            return
        }

        when (event.eventNoticeType) {
            IM_EVENT_TYPE_Read_Message -> {
                // TODO 有变化才更新
                var canBack = false

                getRealm().executeTransactionAsync({

                    val inner: Conversation = it.where<Conversation>().equalTo("id", event.eamtoid).findFirst()!!
                    if (inner.unRead != event.body?.unreadtotals!!) {
                        canBack = true
                        inner.unRead = event.body.unreadtotals!!
                        it.copyToRealmOrUpdate(inner)
                    }

                }, {
                    if (canBack) success?.invoke()
                }, {
                    IMLogErr(it.toString())
                })
            }
        }


    }

    fun handleConversation(list: List<IMChatNotice>, success: OnSuccessCallback? = null) {
        var canBack = false
        getRealm().executeTransactionAsync({

            for (notice in list) {
                when (notice.chatNoticeType) {
                    IM_NOTICE_TYPE_NEW_GROUP,
                    IM_NOTICE_TYPE_MODIFY_GROUP -> {
                        canBack = true
                        val item = IMConvertUtils.convertConversation(notice)
                        it.copyToRealmOrUpdate(item)

                    }
                    IM_NOTICE_TYPE_NEW_MESSAGE -> {
                        canBack = true
                        val inner: Conversation = it.where<Conversation>().equalTo("id", notice.eacgid.toString()).findFirst()!!
                        inner.lastMessageDisplay = notice.eacglastmsg.toString()
                        inner.lastMessageTime = notice.eacglastmsgtime
                        inner.unRead = notice.unreadtotals
                        it.copyToRealmOrUpdate(inner)
                    }
                    IM_NOTICE_TYPE_EXIT_GROUP -> {
                        canBack = true
                        val inner: Conversation = it.where<Conversation>().equalTo("id", notice.eacgid.toString()).findFirst()!!
                        inner.deleteFromRealm()
                    }
                    IM_NOTICE_TYPE_ONLY_EVENT -> {
                        // 不处理
                    }

                }
            }
        }, {
            if (canBack) success?.invoke()
        }, {
            IMLogErr(it.toString())
        })
    }

}